// package
package uit.comm.filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

 

public class HtmlResponseFilter implements Filter 
{
    private FilterConfig config = null;
    private String encoding = "MS949";    // the charset for the response
    private int debug = 0;

    
    public void init(FilterConfig config) throws ServletException 
    {
        this.config = config;
        this.encoding = config.getInitParameter("encoding");
        this.debug = Integer.parseInt(config.getInitParameter("debug"));
    }

    public void destroy() 
    {
        config = null;
        encoding = null;
    }

    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain) throws IOException, ServletException 
    {
        if (request instanceof HttpServletRequest) 
        {
            HttpServletRequest req  = (HttpServletRequest) request;
            HttpServletResponse res = (HttpServletResponse) response;
            String servletPath      = req.getServletPath();
            if (servletPath.endsWith(".html") || servletPath.endsWith(".htm") || servletPath.endsWith(".txt")) 
            {
                HtmlResponseWrapper wrapper = new HtmlResponseWrapper(req, res, encoding, debug);
                chain.doFilter(request, wrapper);
            } else {
				chain.doFilter(request, response);
			}
        }
        else 
        {
            chain.doFilter(request, response);
        }
    }
}
